package com.jwdf.uda.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.databinding.FragmentChangeAvatarBinding;
import com.jwdf.uda.event.ImageSelectorEvent;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UploadImageAction;
import com.jwdf.uda.http.action.UserUpdateInfoAction;
import com.jwdf.uda.photopicker.PhotoPickerActivity;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.dialog.AlertDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.io.File;
import java.util.ArrayList;
import retrofit2.Response;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Administrator on 2016/6/22.
 */
public class ChangeAvatarActivity extends AbsTitleBarActivity {
    public static final int REQ_AVATAR_CHANGE = 0x100;
    public static final int REQ_AVATAR_CROP = 0x101;
    private static final String EXTRA_AVATAR = "avatar";
    public static void start(Context context, String avatar) {
        Intent intent = new Intent(context, ChangeAvatarActivity.class);
        intent.putExtra(EXTRA_AVATAR, avatar);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        return "修改头像";
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new ChangeAvatarFragment();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }
    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putString(EXTRA_AVATAR, getIntent().getStringExtra(EXTRA_AVATAR));
        return args;
    }
    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEvent(IndividualEvent event) {
        finish();
    }

    public static class ChangeAvatarFragment extends BaseFragment {
        private FragmentChangeAvatarBinding mDataBinding;
        private Uri imageUri;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            EventBusUtil.registerEvent(this);
        }
        @Override
        public void onDestroy() {
            EventBusUtil.unregisterEvent(this);
            super.onDestroy();
        }
        public void onEvent(ImageSelectorEvent event) {
            if (ImageSelectorEvent.EVENT_ADD == event.getType() && event.getCode() == REQ_AVATAR_CHANGE) {
                startPhotoZoom(Uri.parse(event.getImages().get(0)));
//                ImageLoader.getInstance().displayImage(event.getImages().get(0), mDataBinding.ivAvatar);
//                mDataBinding.ivAvatar.setTag(R.id.tag_url, event.getImages().get(0));
//                mDataBinding.btnSave.setTag(R.id.tag_url, event.getImages().get(0));
            }
        }
        public void startPhotoZoom(Uri uri) {
            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/avatartemp" + System.currentTimeMillis() + ".jpg"));
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX,outputY 是剪裁图片的宽高
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//图像输出
            intent.putExtra("outputFormat",
                    Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);
            intent.putExtra("return-data", false);//回调方法data.getExtras().getParcelable("data")返回数据为空
            startActivityForResult(intent, REQ_AVATAR_CROP);
        }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            // 截图后返回
            if (requestCode == REQ_AVATAR_CROP && data != null) {
                ImageLoader.getInstance().displayImage(imageUri.toString(), mDataBinding.ivAvatar);
                mDataBinding.ivAvatar.setTag(R.id.tag_url, imageUri.toString());
                mDataBinding.rlSave.setTag(R.id.tag_url, imageUri.toString());
            }
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mDataBinding = FragmentChangeAvatarBinding.inflate(inflater, container, false);
            initViews();
            return mDataBinding.getRoot();
        }
        private void initViews() {
            checkPermission();
            ImageLoader.getInstance().displayImage(getArguments().getString(EXTRA_AVATAR), mDataBinding.ivAvatar);
            mDataBinding.ivAvatar.setTag(R.id.tag_url, getArguments().getString(EXTRA_AVATAR));
            mDataBinding.ivAvatar.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    PhotoView imageView = (PhotoView) view;
                    final ArrayList<String> urls = new ArrayList<>();
                    urls.add((String) imageView.getTag(R.id.tag_url));
                    PhotoActivity.start(view.getContext(), urls, 0);
                }
            });
            mDataBinding.rlChange.setOnClickListener(createOnClickListener());
            mDataBinding.rlSave.setOnClickListener(createOnClickListener());
        }
        @PermissionRequest(100)
        private void checkPermission() {
            String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            if(!RuntimePermission.hasPermissions(getContext(), perms)) {
                RuntimePermission.requestPermissions(this, getString(R.string.app_name), 100, perms);
            }
        }
        private View.OnClickListener createOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch(v.getId()) {
                        case R.id.rl_change:
                            String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                            if(RuntimePermission.hasPermissions(getContext(), perms)) {
                                PhotoPickerActivity.startActivity(getContext(), REQ_AVATAR_CHANGE, new ArrayList<String>(), 1);
                            } else {
                                showAlertNotice();
                            }
                            break;
                        case R.id.rl_save:
                            RelativeLayout btn = (RelativeLayout) v;
                            String image = (String) btn.getTag(R.id.tag_url);
                            if(!TextUtils.isEmpty(image)) {
                                doUploadImageAction(image);
                            } else {
                                getActivity().finish();
                            }
                            break;
                    }
                }
            };
        }
        private void doUploadImageAction(final String image) {
            showProgressDialog();

            UploadImageAction action = new UploadImageAction(getContext(), image,false);
            onNewRequestCall(action.request(new UploadImageAction.IResCallback<String>() {
                @Override
                public void onCallback(int resultCode, UploadImageResponse response) {
                    if (getView() != null) {
                        if (HttpHelper.showError(getContext(), resultCode, response, getString(R.string.error_operation))) {
                            cancelRequest();
                            closeProgressDialog();
                            return;
                        }
                        updateUserInfo(response.getToken());
                    }
                }
            }));
        }
        private void updateUserInfo(String imageToken) {
            onNewRequestCall(UserUpdateInfoAction.newInstance(getContext(), "", "", imageToken).request(new AHttpService.IResCallback<PbBean.PbResUserUpdateInfo>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserUpdateInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
                        closeProgressDialog();
                        if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                            return;
                        }
                        PbBean.PbResUserUpdateInfo info = response.body();
                        IndividualEvent event = new IndividualEvent(IndividualEvent.USER_AVATAR_EVENT);
                        event.userInfo = info.getUserInfo();
                        EventBusUtil.post(event);
                    }
                }
            }));
        }
        private void showAlertNotice() {
            final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msg), new AlertDialog.CallbackListener() {
                @Override
                public void clickYes() {

                }
            });
            alertDialog.show();
        }
    }
}
